<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      size="small"
    >
      <el-form-item label="选手" prop="playerId">
        <el-select
          v-model="queryParams.playerId"
          placeholder="请选择选手"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="item in playerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-switch-button"
          size="mini"
          @click="showGrid = true"
        >
          九宫格预览
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格视图 -->
    <el-table v-loading="loading" :data="voteList" style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" align="center" />
      <el-table-column
        prop="playerName"
        label="选手"
        width="100"
        align="center"
      />
      <el-table-column label="视觉图片" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 60px"
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            fit="cover"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="160"
        align="center"
      />
      <el-table-column label="操作" width="120" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="text" size="small" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 编辑弹窗组件 -->
    <edit-dialog
      :visible.sync="open"
      :title="title"
      :player-options="playerOptions"
      :data="form"
      @submit="handleSubmit"
    />

    <!-- 九宫格预览组件 -->
    <grid-preview
      :visible.sync="showGrid"
      :vote-list="voteList"
      @swap="handleSwap"
      @replace="handleReplace"
      @confirm="handleGridConfirm"
      @success="getList"
    />
  </div>
</template>

<script>
import { listPlayer } from "@/api/player";
import { listVote, addVote, editVote, deleteVote } from "@/api/vote";
import { getFile } from "@/utils/ali-oss";
import EditDialog from "./components/edit.vue";
import GridPreview from "./components/grid.vue";

export default {
  name: "VisionVote",
  components: {
    EditDialog,
    GridPreview,
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 视觉投票列表
      voteList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示九宫格
      showGrid: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        playerId: undefined,
      },
      // 表单参数
      form: {},
      // 选手选项
      playerOptions: [],
    };
  },
  created() {
    this.getList();
    this.getPlayerOptions();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      this.loading = true;
      try {
        const response = await listVote(this.queryParams);
        // 处理每一行数据，获取图片真实地址
        this.voteList = await Promise.all(
          response.rows.map(async (item) => ({
            ...item,
            imageUrl: await getFile(item.vateImages),
          }))
        );
        this.total = response.total;
      } catch (error) {
        console.error("获取列表失败", error);
      } finally {
        this.loading = false;
      }
    },
    /** 获取选手选项 */
    getPlayerOptions() {
      listPlayer().then((response) => {
        this.playerOptions = response.rows.map((item) => ({
          label: item.name,
          value: item.id,
        }));
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.title = "新增视觉投票";
      this.form = {};
      this.open = true;
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.title = "修改视觉投票";
      this.form = { ...row };
      this.open = true;
    },
    /** 提交表单 */
    handleSubmit(formData) {
      const submitMethod = formData.id ? editVote : addVote;
      submitMethod(formData).then(() => {
        this.$modal.msgSuccess("保存成功");
        this.open = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm("是否确认删除该图片？").then(() => {
        deleteVote([row.id]).then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        });
      });
    },
    /** 处理图片交换 */
    handleSwap(fromIndex, toIndex) {
      const updates = [
        { ...this.voteList[fromIndex], sort: toIndex },
        { ...this.voteList[toIndex], sort: fromIndex },
      ];

      Promise.all(updates.map((item) => editVote(item))).then(() => {
        this.$modal.msgSuccess("排序更新成功");
        this.getList();
      });
    },
    /** 处理图片替换 */
    handleReplace(sourceId, targetPlayerId) {
      editVote({
        id: sourceId,
        targetPlayerId: targetPlayerId,
      }).then(() => {
        this.$modal.msgSuccess("替换成功");
        this.getList();
      });
    },
    /** 确认九宫格排序 */
    handleGridConfirm() {
      this.$modal.msgSuccess("保存成功");
      this.getList();
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
